package com.chancein.cloud.report.charts.common.util;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chancein.cloud.report.charts.handler.ReportChartsExceptionHandler;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.SocketException;
import java.net.URL;
import java.nio.charset.StandardCharsets;

import static com.chancein.cloud.report.charts.common.constant.CommonConstant.*;
import static com.chancein.cloud.report.charts.common.constant.OcrDataConstant.*;
import static com.chancein.cloud.report.charts.config.InitParamConfig.*;

/**
 * 请求工具类
 *
 * @author: LiaoZiHao
 * @date: 2023/8/2 18:14
 * Copyright © 2022 Hundsun Technologies Inc. All Rights Reserved
 */
@Deprecated
@Slf4j
public class PostTool {
    /**
     * 发起 OCR 识别请求
     *
     * @date 2023/8/2 18:18
     * @author liaozihao
     * @param requestBody 请求体
     * @param authentication 权限 token
     * @return {@link String}
     */
    @Deprecated
    public static String postOcr(String requestBody, String authentication) {
        try {
            URL url = new URL("");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Accept", "application/json");
            connection.setRequestProperty("Authentication", authentication);
            connection.setDoOutput(true);

            byte[] postData = requestBody.getBytes(StandardCharsets.UTF_8);

            DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
            outputStream.write(postData);
            outputStream.flush();
            outputStream.close();

            int responseCode = connection.getResponseCode();
            // 检查是否存在 504 网关熔断超时错误
            if (responseCode == HttpURLConnection.HTTP_GATEWAY_TIMEOUT) {
                return ReportChartsExceptionHandler.httpGateWayTimeOut504(requestBody, authentication);
            }
            // 检查是否存在 401 token 失效错误
            if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
                return ReportChartsExceptionHandler.httpUnAuthorized401(requestBody);
            }
            // 检查是否存在 500 未知错误
            if (responseCode == HttpURLConnection.HTTP_INTERNAL_ERROR) {
                return ReportChartsExceptionHandler.httpOcrInternalError500(requestBody);
            }
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            StringBuilder response = new StringBuilder();

            while ((line = reader.readLine()) != null) {
                response.append(line);
            }

            reader.close();
            connection.disconnect();

            String responseOcr = response.toString();
            JSONObject resJson = JSON.parseObject(responseOcr);
            String code = resJson.getString(OCR_RSP_CODE);
            String isSuccess = resJson.getString(OCR_RSP_IS_SUCCESS);
            // 检查是否符合公司 500 错误
            if (StrUtil.equals(code, "500") || StrUtil.equals(isSuccess, "false")) {
                return ReportChartsExceptionHandler.httpOcrInternalError500(requestBody);
            }
            // 检查是否是[根本无法解析]的数据
            String ocrData = resJson.getString(OCR_DATA);
            if (StrUtil.equals(code, "0") && StrUtil.equals(ocrData, "{}")) {
                return OCR_RSP_UN_RESOLVE;
            }
            return ocrData;
        } catch (SocketException e) {
            return ReportChartsExceptionHandler.httpSocketException(requestBody, e);
        } catch (IOException e) {
            return ReportChartsExceptionHandler.httpIOException(requestBody);
        }
    }
    /**
     * 发起模拟登录Token请求
     *
     * @date 2023/8/2 18:15
     * @author liaozihao
     * @param requestBody 请求体
     */
    @Deprecated
    public static String postAuth(String requestBody) {
        try {
            URL url = new URL("");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Accept", "application/json");
            connection.setDoOutput(true);

            byte[] postData = requestBody.getBytes(StandardCharsets.UTF_8);

            DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
            outputStream.write(postData);
            outputStream.flush();
            outputStream.close();

            int responseCode = connection.getResponseCode();
            // 检查是否存在 500 未知错误
            if (responseCode == HttpURLConnection.HTTP_INTERNAL_ERROR) {
                return ReportChartsExceptionHandler.httpLoginInternalError500(requestBody);
            }
            // 检查是否存在 404 NotFound 错误
            if (responseCode == HttpURLConnection.HTTP_NOT_FOUND) {
                return ReportChartsExceptionHandler.httpLoginFileNotFound404(requestBody);
            }
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            StringBuilder response = new StringBuilder();

            while ((line = reader.readLine()) != null) {
                response.append(line);
            }

            reader.close();
            connection.disconnect();

            JSONObject authJson = JSON.parseObject(response.toString());
            String auth = authJson.getString(LOGIN_USER_TOKEN);
            if (auth.split(StrUtil.DASHED).length == 5) {
                return auth;
            }
        } catch (FileNotFoundException e) {
            return ReportChartsExceptionHandler.httpLoginFileNotFound404(requestBody);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "SubmitLogin Error!";
    }
}
